﻿using Abp.Authorization;
using Abp.Localization;
using Castle.Core.Internal;
using FutureApp.Authorization.Dto;

namespace FutureApp.Authorization
{
    /// <summary>
    /// 应用程序的权限模块
    /// </summary>
    public class FutureAppAuthorizationProvider : AuthorizationProvider
    {
        private IPermissionDefinitionAppService AppService { get; }
        /// <constructor/>
        public FutureAppAuthorizationProvider(IPermissionDefinitionAppService appService)
        {
            this.AppService = appService;
        }

        /// <summary>
        /// 设置权限
        /// </summary>
        /// <param name="context">权限定义上下文</param>
        public override async void SetPermissions(IPermissionDefinitionContext context)
        {
            var input = new GetAllPermissionDefinitionInput();
            var pdef = await this.AppService.GetAll(input);
            foreach (var def in pdef.Items)
            {
                var permission = context.GetPermissionOrNull(def.Code);
                if(permission == null)
                {
                    permission = context.CreatePermission(def.Code, L(def.Name), L(def.Summary));
                }
                def.Children.ForEach(child => this.CreateChildPermission(child, permission));
            }
        }

        private void CreateChildPermission(PermissionDefinitionEntityDto dto, Permission p)
        {
            var parent = p.CreateChildPermission(dto.Code, L(dto.Name), L(dto.Summary));
            dto.Children.ForEach(child => this.CreateChildPermission(child, parent));
        }

        private static ILocalizableString L(string name)
        {
            return new FixedLocalizableString(name);
        }
    }
}
